// 云函数入口文件
const cloud = require('wx-server-sdk')
const MAX_LIMIT = 100
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  //const wxContext = cloud.getWXContext()

  let spectype = event.spectype;
  return await GetAllSpec(spectype);
}
async function GetAllSpec(spectype) {
  console.log(spectype)
  const countResult = await db.collection('POST_LIST').where({
    spectype: spectype,
    spec: true
  }).count()
  const total = countResult.total
  console.log(total)
  if (total == 0) {
    return {
      data: []
    };
  }
  // 计算需分几次取
  const batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection('POST_LIST').where({
      spectype: spectype,
      spec: true
    }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).orderBy('prior','desc').orderBy('updatetime', 'asc').field({
      htmldata:false
    }).get()
    tasks.push(promise)
  }
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
}